import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'dart:convert';
import '../../class/controller/product_detail.dart';
import '../../components/toast_utils.dart';
import '../../manger/network_utils.dart';
import '../../models/order_detail_model.dart';

class WebViewPage extends StatefulWidget {
  final String title;
  final String url;
  final Map<String, dynamic> oredrArrays;
  final void Function(String)? onOrderIdReceived;

  const WebViewPage({
    Key? key,
    required this.title,
    required this.url,
    this.oredrArrays = const {},
    this.onOrderIdReceived,
  }) : super(key: key);

  @override
  _WebViewPageState createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {
  late WebViewController _controller;
  late WebViewWidget _webView;
  late OrderInfoModel orderInfo;

  @override
  void initState() {
    super.initState();

    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..addJavaScriptChannel('handleBack', onMessageReceived: (JavaScriptMessage message) {
        final messageBody = message.message;
        
        try {
          final decoded = jsonDecode(messageBody);
          if (decoded is Map<String, dynamic>) {
            // 触发订单创建逻辑
            widget.oredrArrays['useepayMsg'] = decoded;
            createOrder();
          }
        } catch (e) {
          print('JSON解析失败: $e');
        }
      })
      ..addJavaScriptChannel('backapp', onMessageReceived: (JavaScriptMessage message) {
        if (message.message.contains('spuId')) {
          final components = message.message.split('=');
          if (components.length > 1) {
            final spuId = components[1];            
            try {
              final number = int.parse(spuId);
              Navigator.pushAndRemoveUntil(
                context,
                MaterialPageRoute(
                  builder: (context) => ProductDetailPage(spuId: number),
                ),
                (route) => route.isFirst,
              );
            } catch (e) {
              print('Error parsing spuId: $e');
            }
          }
        }
      })
      ..addJavaScriptChannel('appCallback', onMessageReceived: (JavaScriptMessage message) {
        ToastUtils.dismissLoadingToast();
        widget.onOrderIdReceived!(orderInfo.orderId);
        Navigator.pop(context);
      })
      ..loadRequest(Uri.parse(widget.url)); // 加载传入的URL

    _webView = WebViewWidget(controller: _controller); // 使用 WebViewWidget 显示 WebView
  }

  // 处理订单创建逻辑
  void createOrder() async {
    ToastUtils.showLoadingToast(context);
    try {
      final response = await NetworkUtils.post(
        RequestCmd.create,
        body: widget.oredrArrays,
      );
      final model = OrderModel.fromJson(response);
      if (model.code == 200) {
        if (model.data?.orderId != null) {
          orderInfo = model.data!;
          if (model.data!.redirectUrl.isNotEmpty) {
            usepayNext();
          } else {
            ToastUtils.dismissLoadingToast();
            widget.onOrderIdReceived!(orderInfo.orderId);
            Navigator.pop(context);
          }
        } 
      } else {
        ToastUtils.showCenterToast(context, model.msg);
      }
    } catch (e) {
      ToastUtils.dismissLoadingToast();
      print(e);
    }
  }

  void usepayNext() {
    try {
      final data = {
        'redirectUrl': orderInfo.redirectUrl,
        'orderId': orderInfo.orderId
      };
      final jsonString = jsonEncode(data);
      final script = 'handleResponse($jsonString);';
      _controller.runJavaScript(script).catchError((error) {
        print('Error executing JavaScript: $error');
        ToastUtils.dismissLoadingToast();
      });
    } catch (e) {
      print('Error serializing JSON: $e');
      ToastUtils.dismissLoadingToast();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title, style: const TextStyle(fontSize: 17)),
      ),
      body: _webView, // 显示 WebView
    );
  }
}
